<?php

namespace App\Models;
use App\Http\Controllers\Pc\ImportController;
use Illuminate\Support\Facades\DB;

class ImportModel extends BaseModel
{
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    }

    public function import($scene, $file, $params = [])
    {
        try {
            // 检查文件是否可以导入
            $PHPExcelLoad = $this->_checkFileType($file);
            // 处理文件导入
            $result = $this->hanleFile($scene, $PHPExcelLoad, $params);
            db::commit();
            return ['code' => 200, 'msg' => 'Import success!' . '导入失败的数据：' . $result];
        }catch (\Exception $e){
            db::rollback();// 回调
            return ['code' => $e->getCode(), 'msg' => 'Import error! Error message:' . $e->getMessage()];
        }
    }

    /**
     * @Desc:检查文件类型是否支持导入
     * @param $file
     * @return \PHPExcel|null
     * @throws \PHPExcel_Reader_Exception
     * @author: Liu Sinian
     * @Time: 2023/2/15 14:56
     */
    private function _checkFileType($file)
    {
        if (empty($file)){
            throw new \Exception( '导入失败，文件为空！', 400);
        }
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

//        var_dump($PHPExcel);

        if (!$PHPExcel->canRead($file)) {
            throw new \Exception( '导入失败，Excel文件错误', 400);
        }

        return  $PHPExcel->load($file);
    }

    /**
     * @Desc:处理导入
     * @param $scene
     * @param $PHPExcelLoad
     * @author: Liu Sinian
     * @Time: 2023/2/15 14:58
     */
    public function hanleFile($scene, $PHPExcelLoad, $params)
    {
        // 开启事务
        db::beginTransaction();
        switch ($scene){
            // 库存sku数量导入
            case ImportController::IMPORT_SCENE['IMPORT_CUSTOM_SKU_NUM']:
                $result = $this->importCustomSkuNum($PHPExcelLoad, $params);
                break;
            case ImportController::IMPORT_SCENE['IMPORT_FASIN_LJDH']:
                $result = $this->importFasinLJDH($PHPExcelLoad, $params);
                break;
        }
        // 保存返回数据
//        $this->saveImportResult($scene, $result);
        return $result;
    }

    public function importFasinLJDH($PHPExcelLoad, $params = [])
    {
        try {
            $Sheet = $PHPExcelLoad->getSheet(0);
            /**取得一共有多少行*/
            $allRow = $Sheet->getHighestRow();

            $allRow = $allRow + 1;
            //循环插入流量数据
            $i = 0;

//            if(!(isset($params['warehouse_name']) && !empty($params['warehouse_name']))){
//                throw new \Exception( '导入失败，缺少仓库名称', 400);
//            }

            // 打印未查询到的sku
            $emptySku = array();
            DB::beginTransaction();
            // 循环处理数据变更
            for ($j = 2; $j < $allRow; $j++) {
                // 获取格式化值
                $fasin = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                $ljdh = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                $shop = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
                $shopMdl = DB::table('shop')->where('shop_name', $shop)->first();
                $fasinBindMdl = DB::table('amazon_fasin_bind')->where('fasin', $fasin)->where('shop_id', $shopMdl->Id ?? 0)->first();
                if ($fasinBindMdl){
                    DB::table('amazon_fasin_bind')->where('fasin', $fasin)->where('shop_id', $shopMdl->Id ?? 0)->update(['fasin_code' => $ljdh, 'fasin' => $fasin, 'shop_id' => $shopMdl->Id ?? 0]);
                }else{
                    DB::table('amazon_fasin_bind')->insert(['fasin_code' => $ljdh, 'fasin' => $fasin, 'shop_id' => $shopMdl->Id ?? 0]);
                }

            }

            DB::commit();

            return '导入成功！';
        }catch (\Exception $e){
            DB::rollback();

            return '导入失败！'.$e->getMessage().';'.$e->getLine();
        }

    }

    /**
     * @Desc:库存sku数量导入
     * @param $PHPExcelLoad
     * @param $params
     * @return true
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/2/15 16:54
     */
    public function importCustomSkuNum($PHPExcelLoad, $params = [])
    {
        $Sheet = $PHPExcelLoad->getSheet(0);
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();

        $allRow = $allRow + 1;
        //循环插入流量数据
        $i = 0;

        if(!(isset($params['warehouse_name']) && !empty($params['warehouse_name']))){
            throw new \Exception( '导入失败，缺少仓库名称', 400);
        }

        // 打印未查询到的sku
        $emptySku = array();

        // 循环处理数据变更
        for ($j = 2; $j < $allRow; $j++) {
            // 获取格式化值
            $sku = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $num = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
//            if($sku==null) continue;
            // 判断格式是否争取
            if(!is_string($sku)){
                throw new \Exception('导入失败，第'.$j.'行,sku格式错误', 400);
            }
            if ($num < 0){
                throw new \Exception( '导入失败，第'.$j.'行,数量格式错误', 400);
            }
            // 查询库存sku是否存在
//            $customSkuModel = Db::table('self_custom_sku')->where('custom_sku',$sku)->orWhere('old_custom_sku',$sku)->first();
//            if (empty($customSkuModel)){
////                throw new \Exception('导入失败，第'.$j.'行,sku:'.$sku.'不存在', 400);
//                $emptySku[] = $sku.',';
//                continue;
//            }
//            $cus= redis::Hget('datacache:go-custom-sku',$sku);

//            $customSkuModel = json_decode($cus,true);
            $customSkuId = $this->GetCustomSkuId($sku);
            if (empty($customSkuId)){
//                throw new \Exception('导入失败，第'.$j.'行,sku:'.$sku.'不存在', 400);
                $emptySku[] = $sku;
                continue;
            }
            // 判断仓库名称
            if ($params['warehouse_name'] == 'QZ'){ // QZ 泉州仓预设标识
                $update = [
                    'quanzhou_num' => $num
                ];
            }elseif ($params['warehouse_name'] == 'TA'){ // 同安仓预设标识
                $update = [
                    'tongan_num' => $num,
                ];
            }else{
                throw new \Exception( '导入失败，仓库名称不在规则内', 400);
            }

            // 更新库存数量
            Db::table('self_custom_sku')->where('id', $customSkuId)->update($update);
        }

        return json_encode($emptySku);
    }

    /**
     * @Desc: 存储导入结果
     * @param $scene
     * @param $result
     * @return true
     * @author: Liu Sinian
     * @Time: 2023/2/16 9:23
     */
    public function saveImportResult($scene, $result)
    {
        Db::table('import_result')->insertGetId([
            'scene' => ImportController::IMPORT_SCENE[$scene],
            'result' => json_encode($result),
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return true;
    }
}